package cn.edu.nju.software.paymentSystem;

import java.util.MissingResourceException;

import org.omg.CORBA.ORB;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;

public class PaymentServer {

	private NamingContextExt ncRef;
	private POA rootPOA;
	private ORB orb;

	/**
	 * init ORB and NameService, create a servant and register it to Name
	 * Service
	 */
	public void init(String name) {
		String initArgs[] = new String[4];
		try {
			initArgs[0] = PaymentOptions.PAYMENT_CORBA_INIT_ARG_0;
			initArgs[1] = PaymentOptions.PAYMENT_CORBA_INIT_ARG_1;
			initArgs[2] = PaymentOptions.PAYMENT_CORBA_INIT_ARG_2;
			initArgs[3] = PaymentOptions.PAYMENT_CORBA_INIT_ARG_3;

			// create and initialize the ORB
			orb = ORB.init(initArgs, null);

			System.out.println("init ORB OK");

			// get reference to rootpoa & activate the POAManager
			rootPOA = POAHelper.narrow(orb
					.resolve_initial_references("RootPOA"));
			rootPOA.the_POAManager().activate();

			// get the root naming context
			org.omg.CORBA.Object objRef = orb
					.resolve_initial_references("NameService");
			// Use NamingContextExt instead of NamingContext. This is
			// part of the Interoperable naming Service.
			ncRef = NamingContextExtHelper.narrow(objRef);

			System.out.println("init NameService OK");

			// create a servant
			SystemCPOAImp csi = new SystemCPOAImp();

			// get CORBA object reference from the servant
			org.omg.CORBA.Object ref = rootPOA.servant_to_reference(csi);
			SystemC sref = SystemCHelper.narrow(ref);

			// bind the Object Reference in Naming
			NameComponent path[];
			path = ncRef.to_name(name);
			ncRef.rebind(path, sref);

			System.out.println("Init Payment Service OK");

		} catch (MissingResourceException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void run() {
		System.out.println("Payment Service is ready...");
		this.orb.run();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		PaymentServer server = new PaymentServer();
		server.init(PaymentOptions.PAYMENT_NAME);
		server.run();
	}

}
